package com.example.tutorial.java.concurrent.practice.ch6;

import java.util.concurrent.*;

/**
 * ExecutorCompletionService适用场景：
 * 向Executor提交一组任务，并希望在计算完成后获取结果
 *
 * @author: cph
 * @date: 2022-4-23
 */
public class CompletionServiceTest {


    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(executor);

        int taskNum = 3;
        for (int i = 0; i < taskNum; i++) {
            completionService.submit(new MyTask(i));
        }

        for (int i = 0; i < taskNum; i++) {
            Future<String> take = completionService.take();
            String result = take.get();
            System.out.println(result);
        }

    }

    static class MyTask implements Callable<String> {

        private Integer num;

        public MyTask(Integer num) {
            this.num = num;
        }

        @Override
        public String call() throws Exception {
            Thread.sleep(2000L);
            return num + ": " + Thread.currentThread().getName();
        }
    }
}
